﻿#include "ICommand.h"

#include "../../Utils/Logger.h"
#include "CommandsManager.h"
// void ICommand::registerAlias(std::u8string_view str) {
// }
//
// void ICommand::clientMessageF(std::u8string_view str) {
// }

float ICommand::assertFloat(std::u8string_view string) {
	return std::stof(std::string{*reinterpret_cast<std::string_view*>(&string)});
}

ICommand::ICommand(std::u8string_view com, std::u8string_view usage, std::array<std::u8string_view, languagesize> des, std::initializer_list<std::u8string> nameTable, fast_io::vector<aliasList_struct> al, void (*_init)(ICommand*), bool (*_onExecute)(const fast_io::vector<std::u8string>&)) 
	: _command(com), _usage(usage), _description(std::move(des)), aliasList(std::move(al)), init(_init), onExecute(_onExecute) {

	if (_onExecute == nullptr) [[unlikely]] {
#ifdef _DEBUG
		__debugbreak();
#else
		fast_io::fast_terminate();
#endif  // _DEBUG
	}

	std::u8string temp{com};  // commands
	std::ranges::for_each(temp, [](char8_t& str) { str = fast_io::char_category::to_c_lower(str); });
	CommandMgr::NameTable[std::move(temp)] = this;
	
	for (auto& i : nameTable) {
		auto& k = const_cast<std::u8string&>(i);
		std::ranges::for_each(k, [](char8_t& str) { str = fast_io::char_category::to_c_lower(str); });
		CommandMgr::NameTable[std::move(k)] = this;
	}
}

void ICommand::_init() {
	if (init) {
		[[maybe_unused]] auto lock = std::shared_lock(iCommandLook);
		init(this);
	}
}

bool ICommand::_onExecute(const fast_io::vector<std::u8string>& args) {
	bool successful = false;
	if (onExecute) [[likely]] {
		[[maybe_unused]] auto lock = std::shared_lock(iCommandLook);
		try {
			successful = onExecute(args); 
		} catch (...) { // throw bug
			successful = false;
		}
	}
	return successful;
}
